<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <title>业务验证</title>

    <!-- placeholders for the theme switcher -->
    <link rel='stylesheet' id='icon_stylesheet'>
    <script src='jquery-1.9.1.min.js'></script>

    <!-- <link rel="stylesheet" href="/bootstrap-combined.min.css"> -->
    <link rel="stylesheet" href="/bootstrap3.2full.css">
    <script src="/sceditor/jquery.sceditor.bbcode.min.js"></script>
    <link rel="stylesheet" href="/sceditor/jquery.sceditor.default.min.css">
    <script src="/sceditor/jquery.sceditor.xhtml.min.js"></script>
    <link rel="stylesheet" href="/sceditor/themes/default.min.css">
    
    <style>[class*="foundicon-"] {font-family: GeneralFoundicons;font-style: normal;}</style>
    <script src='dist/jsoneditor.js'></script>
    <script src='widget/widgetdef.js'></script>
    <script src='widget/metacommon.js'></script>
    <script src='widget/meta2util.js'></script>
    <script src='widget/meta2content_util.js'></script>
</head>
<body onload="javascript:initEnv()"> <br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;参数设置人员级别：
<select id="setterLevel">
    <option value="1">集团</option>
    <option value="2">省级</option>
</select> 
&nbsp;&nbsp;&nbsp;&nbsp;|| 
是否为单一运营级别<input type="checkbox" id="isSingleOp" onclick="javascript:setSingleOpMode(this);">
运营级别：<select id="singleOpLevel" disabled="true">
    <option value="1">集团</option>
    <option value="2">省级</option>
    <option value="3">地市</option>
</select>
&nbsp;&nbsp;&nbsp;&nbsp;|| 
页面发布级别：<select id="pageDistLevel" >
    <option value="1">集团</option>
    <option value="2">省级</option>
    <option value="3">地市</option>
</select>
</br>

<div class='container'>
    <div class='row' >
        <div class='span8 col-md-8 columns eight large-8' style="width:100%;">
            <h2></h2>
            <p></p>

            <div id='editor'></div>
        </div>
        <div class='row'>
            <div class='span12 col-md-12 columns twelve large-12'>
                <h2>页面数据模型</h2>
                <p> <button class='btn btn-primary' id='setschema'>更新数据模型定义</button> &nbsp;&nbsp;&nbsp;&nbsp;
                 <button class='btn btn-primary' id='loadSchema'>装载数据模型</button></p>

                <textarea id='schema' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
         
            </div>
        </div>

        <div class='row'>
            <div class='span12 col-md-12 columns twelve large-12'>
                <h2>最终数据模型定义（含运营参数）</h2>
                <p> <button class='btn btn-primary' id='updateContentDef'>更新内容定义页面</button>

                   &nbsp;&nbsp;<input type="button" value="页面数据装载" class='btn btn-primary' id='reloadMetaContent'/></p>

                <textarea id='output' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
            扩展业务数据：<br><textarea id='ext_schema' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
 
            输出schema：
                <textarea id='output_schema' style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
            
            <br/>
            </div>
        </div>
        <div class='span8 col-md-8 columns eight large-8' style="width:100%;">
            <h2>页面内容输入</h2>
            <p>这是最终的页面内容的输入区域</p>

            <div id='contenteditor'></div>
        </div>

        <div class='row'>
            <div class='span12 col-md-12 columns twelve large-12'>
            <form method="POST"  action="index.jsp">
                    <h3>最终内容数据 </h3>
                    <h4>
                    | 选择编辑区域：
                    <select id="sltPageArea" >
                        <option value="" selected="">请选择</option>
                    </select>
                    | 选择编辑人员级别：
                    <select id="sltEditorLevel" >                        
                        <option value="" selected="">请选择</option>
                        <option value="1">集团</option>
                        <option value="2">省级</option>
                        <option value="3">地市级</option>
                    </select>
                    </h4>
                 <textarea id='output_cnt'  name="output_cnt" style='width: 100%; height: 200px; font-family: monospace;' class='form-control'></textarea>

            扩展页面业务数据：<br><textarea id='ext_cnt' name="ext_cnt" style='width: 100%; height: 100px; font-family: monospace;' class='form-control'></textarea>
                   <p> <button class='btn btn-primary' id='updateContent'>预览页面</button> 
                   &nbsp;&nbsp;<input type="button" value="页面数据装载" class='btn btn-primary' id='reloadContent'/>                   
                   &nbsp;&nbsp;<input type="button" value="生成扩展数据" class='btn btn-primary' id='genExtCnt' /></p>
               </form>
            </div>
        </div>
  
    </div>
</div>       
<script>
schema = {"type":"string","title":"test"};

    // Divs/textareas on the page
    var $schema = document.getElementById('schema');
    var $output = document.getElementById('output');
    var $output_cnt = document.getElementById('output_cnt');
    var $editor = document.getElementById('editor');
    var $validate = document.getElementById('validate');

    var $contenteditor = document.getElementById("contenteditor");

    // Buttons
    var $set_schema_button = document.getElementById('setschema');
    var $load_schema_button = document.getElementById('loadSchema');
    var $load_content_button = document.getElementById("updateContent");
    var $set_value_button = document.getElementById('setvalue');




    var gReload = null;
    var mark = 1;
(function() {

//       themecss = '/bootstrap3.2full.css';// 
        // document.getElementById('theme_stylesheet').href = themecss;
        theme = 'bootstrap3';// 
        JSONEditor.defaults.options.theme = theme;

    var jsoneditor;
 
    var reload = function(keep_value) {
        var startval = (jsoneditor && keep_value)? jsoneditor.getValue() : window.startval;
        window.startval = undefined;

        if(jsoneditor) jsoneditor.destroy(); 
        jsoneditor = new JSONEditor($editor,{
            schema: schema,
            startval: startval,
            ajax:true,
            disable_edit_json:true,
            disable_properties:true,
            collapse:true
            // threme:'bootstrap2'
        });
        gReload = reload;
        window.jsoneditor = jsoneditor;

        // When the value of the editor changes, update the JSON output and validation message
        jsoneditor.on('change',function() {
            var json = jsoneditor.getValue();

            $output.value = JSON.stringify(json,null,2);

            var validation_errors = jsoneditor.validate($output.value);
            // Show validation errors if there are any
            if(validation_errors.length) {
//                 $validate.value = JSON.stringify(validation_errors,null,2);
                // console.log("validate result:" + JSON.stringify(validation_errors,null,2));
            }
            else {
//                 $validate.value = 'valid';
                // console.log("validate result: valid" )
            }
         });

         jsoneditor.on('ready',postMetaReadyFunc);
    };


    var $metaCntSetting = document.getElementById("reloadMetaContent");
    $metaCntSetting.addEventListener("click",function(){
         jsoneditor.setValue(JSON.parse($output.value)); 

        var setterLevel = "1";
        var slt = document.getElementById("setterLevel");
        if(slt){
            setterLevel = slt.options[slt.selectedIndex].value;
        }
        scanMeta2Level(jsoneditor,setterLevel,null)
    });


    $load_schema_button.addEventListener("click",function(){
        try{
            
        if(pagemeta.inited != false ) 
            pagemeta.init();
            $schema.value = "";
            //var stringMeta = pagemeta.loadPageMetaMetaDef("/4G/4gpageMeta_array.json"); //复杂类型
           var stringMeta = pagemeta.loadPageMetaMetaDef("/4G/4gpageMeta.json");   //4G
//             var stringMeta = pagemeta.loadPageMetaMetaDef("/4G/TypeSysShow.json") ;//基础类型
            $schema.value = stringMeta;
        }
        catch(e){         
            alert('error on loading Schema from file: '+e.message);
            throw e;
        }
    });

 
    // Update the schema when the button is clicked
    $set_schema_button.addEventListener('click',function() {
        try {
            schema = JSON.parse($schema.value);
        }
        catch(e) {
            alert('Invalid Schema: '+e.message);
            return;
        }

        reload();
        //是否为单一运营级别，如果是，将载入的权限全部设置为单一指定的级别
        var singleMode = document.getElementById("isSingleOp").checked;
        if(singleMode){
           var slt = document.getElementById("singleOpLevel");
            var singleOpLevel = slt.options[slt.selectedIndex].value;
            if(singleOpLevel){
                
                var setterLevel = "3";  
                scanMeta2Level(jsoneditor,setterLevel,true)
            }  
        }
        else{   //设置第一级为集团，默认
           initOpLevel(jsoneditor); 
        }
    });

 //    reload();
})();




//content editor area:
    var jsoneditor_cnt;

    var cnt_schema = {"type":"string","title":"test"};

    var reload_cnt = function(keep_value) {
        var startval = (jsoneditor_cnt && keep_value)? jsoneditor_cnt.getValue() : window.startval;
        window.startval = undefined;
        JSONEditor.plugins.sceditor.emoticonsEnabled = false;
        JSONEditor.plugins.sceditor.toolbarExclude = "youtube,emoticon";
         if(jsoneditor_cnt) jsoneditor_cnt.destroy();
        jsoneditor_cnt = new JSONEditor($contenteditor,{
            schema: cnt_schema,
            startval: startval,
            ajax:true,
            disable_edit_json:true,
            disable_properties:true,
            collapse:true
        });
        window.jsoneditor_cnt = jsoneditor_cnt;
        jsoneditor_cnt.on("ready",postCntReadyFunc);

        // When the value of the editor changes, update the JSON output and validation message
        jsoneditor_cnt.on('change',function() {
            var json = jsoneditor_cnt.getValue();

            $output_cnt.value = JSON.stringify(json,null,2);

            var validation_errors = jsoneditor_cnt.validate();
            // Show validation errors if there are any
            if(validation_errors.length) {
                //$validate.value = JSON.stringify(validation_errors,null,2);
//                 console.log("content json validate result: " + JSON.stringify(validation_errors,null,2));
            }
            else {
                //$validate.value = 'valid';
                console.log("content json validate result: valid!")
            }
         });
    };


function fetchPageMetaParam(){
    return $output.value;
}

    var $load_content_def_button = document.getElementById('updateContentDef');
var schemaPage = null;
    // Update the schema when the button is clicked
    $load_content_def_button.addEventListener('click',function() {
            var cnt_schema_str = loadPageParams();
            cnt_schema = JSON.parse(cnt_schema_str);
            //setting output schema to page;
            document.getElementById("output_schema").value = cnt_schema_str;
        try {
            ;
        }
        catch(e) {
            alert('Invalid Schema: '+e.message);
            return;
        }

        reload_cnt();
        fillPageAreaInfo();
    });

    var $reloadContent = document.getElementById("reloadContent");
    $reloadContent.addEventListener("click",function(){
        var cnt = document.getElementById("output_cnt").value;
        if(cnt){
            jsoneditor_cnt.setValue(JSON.parse(cnt));
        } 
        
        restoreCntExt(jsoneditor_cnt,document.getElementById("ext_cnt").value);
        return false;
    });

    //验证编辑级别和编辑页面区域：
    $sltPageArea = document.getElementById("sltPageArea");
    $sltPageArea.addEventListener("change",function(){
        //change page area
        var title = this.options[this.selectedIndex].value;
        if(title){           
        for(var i in cnt_schema.properties.pageBlocks.properties){ 
            var path = "root.pageBlocks."+i;
            var o = jsoneditor_cnt.getEditor(path);
            var b = o.toggle_button;
            if(title === i ){
                if(b.innerHTML === '展开'){
                    _fire(b,"click");
                    // b.disabled = false;
                }
                b.disabled = false;
            }
            else{   //not selected area
                if(b.innerHTML === "收起"){
                    _fire(b,'click');
                } 
                    b.disabled = true;
            } 
        }
            //
        }
    });
    function fillPageAreaInfo(){
        sltPageArea.options.length = 0;
        sltPageArea.add(new Option("请选择",""))
        var idx = 0;
        for(var i in cnt_schema.properties.pageBlocks.properties){
            var o = cnt_schema.properties.pageBlocks.properties[i];
            sltPageArea.add(new Option(o.title,i));
            idx++;
        }
    };

    var userLevel = "1";
    $sltEditorLevel = document.getElementById("sltEditorLevel");
    $sltEditorLevel.addEventListener("change",function(){
        //change editor level
        var pageParams = $output.value;
        if(!pageParams){
            alert("请先设置页面参数信息");
            return;
        }
        jsoneditor_cnt.getEditor("root").disable();

        if(this.options[this.selectedIndex].value){
            userLevel = this.options[this.selectedIndex].value;
            var path = "pageBlocks";
            //travel(JSON.parse(pageParams),path);
            var authInfo = new Auth4Level(userLevel,"");
            findAuth4Level(JSON.parse(pageParams),path,authInfo);
            //console.debug(authInfo);
            testAuthInfoVisit(authInfo,"\t","root");
            setEditor4Level(jsoneditor_cnt,authInfo,"root");
        }
    });


    function setArray4Level(ai,ppath){
        var pp =  ai.parentPath;
        pp = ppath +  (pp === ""?"":"."+pp) ;
        for(var i =0; i < searchLevel;i++){
            var arrayIdxPath = pp + "." +  i;
            var arrayIns = jsoneditor_cnt.getEditor(arrayIdxPath);
            if(!arrayIns)   break;

            // for()            
        }
    }



    function testAuthInfoVisit(authInfo,preIdens,parentPath){
        // var idens = 0;
        for(var fp in authInfo.flatPath){
            console.log(preIdens +">" + parentPath + "." + authInfo.flatPath[fp]);        
        }
        var i =0;
        for(var a in authInfo.arrayPath){
            var ai = authInfo.arrayPath[a];
            var pi = preIdens + "\t" ;
            var pp = parentPath + "."+ai.parentPath + "." + i;
            console.log(pi + ">"+pp +".");
            testAuthInfoVisit(ai,pi,pp);
            i++;
        }
    }



    //     var metaMark = "bizMeta";
    //     var levelMark = "distLevel";

    // function visitNode(node,path){
    //     if(node){
    //         if(Array.isArray(node)){
    //             var ii = 0;
    //             for(var nn in node){
    //                 visitNode(node[nn],path+"["+ii+"]");
    //                 ii++;
    //             }
    //         }
    //         if(window.isplainobject(node)){
    //             if(node[metaMark] && node[metaMark][levelMark]){
    //                 var lv = node[metaMark][levelMark];
    //                 var pageObjs = document.getElementsByName(path);    
    //                 for(var po in pageObjs){                        
    //                     if(lv === currentLevel){                         
    //                         po.disabled = true;   
    //                     }
    //                     else
    //                         po.disabled = false;
    //                 }
    //             }
    //             else{
    //                 for(var nn in node){
    //                     if(nn === metaMark) return "";
    //                     visitNode(node[nn],path+"["+nn+"]");
    //                 }
    //             }
    //         }
    //         //raw type,return;
    //         return "";
         
    //     }
    // }

    function setSingleOpMode(ctl){
       var slt = document.getElementById("singleOpLevel"); 
       var slt1 = document.getElementById("sltEditorLevel"); 
        if(ctl.checked){
            slt.disabled = false;
            slt1.disabled = true;
        }
        else{
            slt.disabled = true;
            slt1.disabled = false;
        }
    }

    function initEnv(){
        var ctl = document.getElementById("genExtCnt");
        if(ctl){
            ctl.addEventListener('click',genExtCnt);
        }
    }
</script>
</body>
</html>
